package com.xiefengf.elasticsearch.jd.service;

import com.xiefengf.elasticsearch.jd.model.Content;
import com.xiefengf.elasticsearch.jd.utils.HtmlParseUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiefengf
 * @version 1.0
 * @date 2024/4/6 23:13
 *
 * 业务编写
 */
@Service
public class ContentService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;

    /**
     * 解析JD网页数据同时放入ES索引中
     * @param keyword
     * @return
     */
    public Boolean parseContent(String keyword){
        // 1、JSOUP解析京东网页数据（实际应用场景，这里的数据来源可能是Mysql、MQ、Log等等）
        List<Content> contentList = HtmlParseUtils.parseJD(keyword);
        // 2、创建ES的索引
        // 2.1 索引操作器
        IndexOperations indexOps = elasticsearchTemplate.indexOps(Content.class);
        // 2.2 是否存在，存在则先删除
        if (indexOps.exists()) {
            indexOps.delete();
        }
        // 2.3 创建索引
        indexOps.create();
        // 2.4 根据实体类获取映射关系
        Document mapping = indexOps.createMapping(Content.class);
        // 2.5 将映射关系添加至索引中
        indexOps.putMapping(mapping);
        // 3、为索引创建文档
        elasticsearchTemplate.save(contentList);
        return Boolean.TRUE;
    }

    /**
     * 条件搜索
     * @param field
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<Content> searchPage(String field,String value,int pageNo,int pageSize){
        // 构建精确查询条件
        TermQueryBuilder termQuery = QueryBuilders.termQuery(field,value);
        NativeSearchQuery searchQuery = new NativeSearchQuery(termQuery);
        searchQuery.setPageable(PageRequest.of(pageNo, pageSize));
        // 条件查询
        List<SearchHit<Content>> toList = elasticsearchTemplate.search(searchQuery, Content.class).toList();
        // 返回结果
        return toList.stream().map(SearchHit::getContent).collect(Collectors.toList());
    }

}
